import os
import pandas as pd
import requests

# 配置
FOLDER_PATH = "D:\\project_file\\app我的优化\\我的页面icon"  # 替换为你的文件夹路径
EXCEL_PATH_OUT = "D:\\project_file\\app我的优化\\生产-icon表格完善.xlsx"  # 替换为你的 Excel 文件路径
API_URL = "http://filegateway.ewt360.com/api/filecenter/fileService/saveFile"  # 替换为实际接口地址
BIZ_TYPE_COLUMN = "业务类型"  # Excel 中业务类型列名
ICON_URL_COLUMN = "图标url"  # Excel 中图标 URL 列名
FILE_DIR = "1056/2025/10/19/"  # 文件存储路径

# 读取 Excel 文件
try:
    df = pd.read_excel(EXCEL_PATH_OUT)
except Exception as e:
    print(f"读取 Excel 文件失败: {e}")
    exit(1)

# 确保必要的列存在
if BIZ_TYPE_COLUMN not in df.columns or ICON_URL_COLUMN not in df.columns:
    print(f"Excel 文件必须包含 '{BIZ_TYPE_COLUMN}' 和 '{ICON_URL_COLUMN}' 列")
    exit(1)


df[ICON_URL_COLUMN] = df[ICON_URL_COLUMN].astype("string")

# 获取业务类型列的值（去除空值）
biz_types = df[BIZ_TYPE_COLUMN].dropna().astype(str).tolist()
i = 40
# 遍历文件夹中的文件
for filename in os.listdir(FOLDER_PATH):
    file_path = os.path.join(FOLDER_PATH, filename)

    # 确保是文件而非文件夹
    if not os.path.isfile(file_path):
        continue

    # 检查文件名是否包含业务类型
    matched_biz_type = None
    for biz_type in biz_types:
        if biz_type in filename:
            matched_biz_type = biz_type
            break

    if matched_biz_type:
        file_path_url = None
        print(f"找到匹配文件: {filename} (业务类型: {matched_biz_type})")

        # 构造 multipart/form-data 请求
        data = {
            "bizType": 1056,
            "fileDir": FILE_DIR+str(i).zfill(3)
        }
        files = {
            "fileData": (filename, open(file_path, "rb"), "image/jpeg")  # 假设为图片，调整 MIME 类型如需要
        }

        try:
            # 发起 POST 请求
            response = requests.post(API_URL, files=files, data=data)

            if response.status_code == 200:
                response_json = response.json()
                if response_json.get("success", False):
                    file_path_url = response_json.get("data", {}).get("filePath")
                    print(f"文件 {filename} 上传成功，filePath: {file_path_url}")

                    # 回写图标 URL 到 Excel
                    # 找到匹配 bizType 的行
                    for index, row in df.iterrows():
                        if str(row[BIZ_TYPE_COLUMN]) == matched_biz_type:
                            df.at[index, ICON_URL_COLUMN] = file_path_url
                else:
                    print(f"文件 {filename} 上传失败，错误信息: {response_json.get('msg', '未知错误')}")
            else:
                print(f"文件 {filename} 上传失败，状态码: {response.status_code}, 响应: {response.text}")

        except requests.exceptions.RequestException as e:
            print(f"文件 {filename} 上传发生错误: {e}")

        finally:
            # 关闭文件
            if "fileData" in files:
                files["fileData"][1].close()

# 保存更新后的 Excel 文件
try:
    df.to_excel(EXCEL_PATH_OUT, index=False)
    print(f"Excel 文件已更新: {EXCEL_PATH_OUT}")
except Exception as e:
    print(f"保存 Excel 文件失败: {e}")

